﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SiChuan.FormsApp.AppCode.Extensions;
using SiChuan.FormsApp.AppCode.Exceptions;
using Newtonsoft.Json;
using SiChuan.FormsApp.AppCode.Models;

namespace SiChuan.FormsApp.AppCode.Helpers {

    public static class ApiHelper {

        static string _url = Constants.ApiUrl;

        public static async Task<string> ApiResponseAsync(this string url, Dictionary<string, object> body) {
            var res = await (_url + url).PostAsync(body);
            if (res.Item1) {
            } else {
                throw new WarnException("【请求错误】" + res.Item2);
            }
            try {
                var data = JsonConvert.DeserializeObject<ApiResponseModel>(res.Item2);
                if (data.Code != 1) {
                    throw new WarnException("【返回错误】" + data.Message);
                }
                if (data.Data == null) {
                    return "";
                }
                if (data.Data.GetType().Name.Equals("string", StringComparison.OrdinalIgnoreCase)) {
                    return data.Data.ToString();
                }
                var resString = JsonConvert.SerializeObject(data.Data);
                return resString;
            } catch {
                throw new WarnException("【返回数据转化出错】" + res.Item2);
            }
        }

        public static async Task<T> ApiResponseAsync<T>(this string url, Dictionary<string, object> body) where T : class {
            var res = await ApiResponseAsync(url, body);
            var model = JsonConvert.DeserializeObject<T>(res);
            return model;
        }

        /// <summary>
        /// 获取要上报的xml
        /// </summary>
        /// <param name="url"></param>
        /// <param name="body"></param>
        /// <returns></returns>
        public static async Task<Tuple<bool, string>> ApiGetSenderDataAsync(this string url, Dictionary<string, object> body) {
            var data = await ApiResponseAsync(url, body);
            if (data == null || data.LastIndexOf("ook") > -1) {
                return new Tuple<bool, string>(false, data.Split(',')[1]);
            } else {
                return new Tuple<bool, string>(true, data);
            }
        }
    }
}
